from rest_framework import serializers
from .models import UserProfile
from django.contrib.auth import authenticate
from django.contrib.auth.hashers import make_password, check_password


# 用户登录 序列化类
class UserSerializer(serializers.ModelSerializer):
    username = serializers.CharField(max_length=11)
    password = serializers.CharField(write_only=True, required=False)
    user_id = serializers.CharField(required=False)

    def validate(self, attr):
        user = authenticate(username=attr["username"], password=attr["password"])
        if user:
            attr['user'] = user
            return user
        else:
            username_user = UserProfile.objects.filter(username=attr["username"]).first()
            if username_user:
                raise serializers.ValidationError(detail="密码错误...", code="kq")
            else:
                raise serializers.ValidationError(detail="用户不存在", code="kq")

    class Meta:
        model = UserProfile
        fields = ('username', 'password','user_img','user_id','mobile','last_login',)

